<?php
namespace iBrand\Shop\Server\Http\Controllers;

use iBrand\Server\Http\Controllers\Controller;
use iBrand\Shop\Core\Models\Clerk;
use iBrand\Shop\Core\Models\Shop;

use iBrand\Shop\Core\Models\WeQrCode;
use iBrand\Shop\Core\Repositories\ClerkRepositoryEloquent;
use iBrand\Shop\Core\Repositories\O2oGoodsRepository;
use iBrand\Shop\Core\Repositories\OrderRepository;

use iBrand\Server\Exception\UserExistsException;
use Illuminate\Auth\Events\Login;
use Illuminate\Http\Request;
use League\OAuth2\Server\Exception\OAuthServerException;
use RuntimeException;
use Validator;
use Hash;


class HomeController extends Controller
{

    protected $clerkRepository;
    protected $WeQrCode;
    protected $orderRepository;
    protected $o2oGoodsRepository;

    public function __construct(
        ClerkRepositoryEloquent $clerkRepository
        , WeQrCode $WeQrCode
        , OrderRepository $orderRepository
        , O2oGoodsRepository $o2oGoodsRepository
    )
    {
        $this->clerkRepository = $clerkRepository;
        $this->WeQrCode = $WeQrCode;
        $this->orderRepository = $orderRepository;
        $this->o2oGoodsRepository = $o2oGoodsRepository;
    }


    public function index()
    {
        $clerk = auth('clerk')->user();
        $shop_id = $clerk->shop_id;
        $data = [];
        $clerk_info = $this->clerkRepository->getShopInfoById($clerk->id);
        if ($clerk_info->avatar) $clerk_info->avatar = url($clerk_info->avatar);
        $data['clerk'] = $clerk_info;
        if ($clerk->is_clerk_owner) { //如果是店长
            $order_count = $this->orderRepository->getOrderCountMonthByClerkIDorShopID($clerk->shop_id, true, $shop_id);
            $order_total = $this->orderRepository->getOrderTotalMonthByClerkIDorShopID($clerk->shop_id, true, $shop_id);
        } else { //店员
            $order_count = $this->orderRepository->getOrderCountMonthByClerkIDorShopID($clerk->id, false, $shop_id);
            $order_total = $this->orderRepository->getOrderTotalMonthByClerkIDorShopID($clerk->id, false, $shop_id);
        }
        $data['order_count'] = $order_count;
        $data['order_total'] = $order_total;
        $data['goods_count'] = $this->o2oGoodsRepository->findWhere(['shop_id' => $shop_id, 'status' => 1])->count('store_nums');


        return $this->api($data, true, 200, '');
    }

    public function getClerkQRCode($shop_id)
    {
        $clerk = auth('clerk')->user();
        $str = 'O2O_shop##' . $shop_id . '##' . $clerk->id;
        if ($res = $this->WeQrCode->where('scene_str', 'like', '%' . $str . '%')->first()) {
            return $this->api(['code' => $res->qr_code_url], true, 200, '');
        };
        return $this->api([], false, 400, '二维码生成失败，请联系管理员后台生成二维码');
    }


}